﻿/// <reference path="Interpolaters.js" />
/*
    Name:           Value Noise
    Description:
                    This library provides the implementation
                    of various different interpolation techniques
    Date: 2014/02/07
    Version: 0.0.1
    Author: Dave Russell 
*/
ValueNoise = new function () {

    this.RandomArray = new Array();
    this.Size = 512;

    this.Init = function (dimensions, size, array) {
        array = new Array(size);
        if (dimensions == 1) {          
            for (var i = 0; i < size; i++) {
                array[i] = Math.random();
            }
            return array;
        } else {
            array = new Array(size);
            for (var i = 0; i < size; i++) {
                var nd = dimensions - 1;
                array[i] = this.Init(nd, size, array[i]);
            }
            return array;
        }
    };
        
    this.Get1D = function(x){
        if(this.RandomArray.length == 0){
            this.RandomArray = this.Init(1,this.Size, this.RandomArray);
        }

        var xmin = Math.floor(x) % this.RandomArray.length;
        var t = x - xmin;
        return Interpolaters.Linear(this.RandomArray[xmin], this.RandomArray[xmin + 1], t);
    };

    this.Get2D = function (x, y) {
        if (this.RandomArray.length == 0) {
           this.RandomArray=  this.Init(2, this.Size, this.RandomArray);
        }
        
        var xmin = Math.floor(x) % this.Size;
        var ymin = Math.floor(y) % this.Size;

        var tx = x - xmin;
        var ty = y - ymin;
        
        /// Random values at the corners of the cell
        var rx0 = xmin & (this.Size -1);
        var rx1 = (xmin + 1) & (this.Size -1);
        var ry0 = ymin & (this.Size - 1);
        var ry1 = (ymin + 1) & (this.Size - 1);

        var sx = tx * tx * (3 - (2 * tx));
        var sy = ty * ty * (3 - (2 * ty));

        var p00 = this.RandomArray[rx0][ry0];
        var p01 = this.RandomArray[rx0][ry1];
        var p10 = this.RandomArray[rx1][ry0];
        var p11 = this.RandomArray[rx1][ry1];

        var pl0 = Interpolaters.Linear(p00, p10, sx);
        var pl1 = Interpolaters.Linear(p01, p11, sx);

        return Interpolaters.Linear(pl0, pl1, sy);
    };

    this.Reinit = function () {
        this.RandomArray = new Array();
    }

};